package com.xiaolong.shiro;

import javax.annotation.Resource;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

import com.xiaolong.model.SysPermission;
import com.xiaolong.model.SysRole;
import com.xiaolong.model.SysUser;
import com.xiaolong.server.ISysUserService;

public class MyShiroRealm extends AuthorizingRealm {

	@Resource
	private ISysUserService userService;
	
	/**
	 * 权限控制
	 */
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
		SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
		SysUser user = (SysUser) principalCollection.getPrimaryPrincipal();
		for(SysRole role:user.getRoles()){
			authorizationInfo.addRole(role.getRoleName());
			for(SysPermission permission:role.getPermissions()){
				authorizationInfo.addStringPermission(permission.getPermission());
			}
		}
		return authorizationInfo;
	}

	/**
	 * 身份认证
	 */
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
		UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken; 
		String userName = (String) token.getPrincipal();
		System.out.println(userName+"----"+authenticationToken.getCredentials());
		SysUser user = userService.findUserByUsername(userName);
		if(user == null) {  
            throw new UnknownAccountException();//没找到帐号  
        } 
		SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(
				user, //用户名
				user.getPassword(), //密码
	                getName()  //realm name
	        );
		return authenticationInfo;
	}

}
